import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import Editor from '@/utils/Editor';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Col,
  Card,
  Icon,
  Tooltip,
  Form,
  Button,
  Input,
  Spin,
  Table,
  message,
  InputNumber,
  Modal,
  Select,
  Drawer,
  DatePicker,
} from 'antd';
import styles from './index.less';

const Search = Input.Search;
const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
const { MonthPicker, RangePicker } = DatePicker;
const monthFormat = 'YYYY/MM';

class EditorDrawer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      content: '',
      login: false,
      selectPd: '财务指标',
      timeCs: String(moment().format('YYYY-MM')),
      selectList: [],
      init: '经营情况',
      valueA:'',
      textList: [
        // { name: '请选择', title: '', getName: 's1electName', textName: 't1extName' },
      ],
      // textLists: [{ name: '请选择', title: '', getName: 's1electName', textName: 't1extName' }],
      arr: [],
      judge: true,
      initalTime: moment(String(moment().format('YYYY-MM')), 'YYYY-MM'),
    };
  }

  componentDidMount() {
    this.getDictWordList();
    const { dispatch } = this.props;
    const { textList } = this.state;
    console.log(this.props.bjTime);
    const a = [];
    this.setState({
      arr: [],
      judge: true,
    });
    if (this.props.bjTime !== '1') {
      // 编辑
      const { reportType, endTime } = this.props.bjTime;
      this.props.bjTime.data.map((item, index) => {
        let b = {};
        b.name = item.name;
        b.value = item.value;
        b.key = index;
        a.push(b);
      });
      this.setState(
        {
          textList: a,
          initalTime: moment(String(moment(endTime).format('YYYY-MM')), 'YYYY-MM'),
          reportType,
        },
        () => {
          console.log(this.state.textList);
        }
      );
    }
  }

  getDictWordList = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'businessKnowledgeBase/getDictWordList',
        payload: { robotId: currentUser.robotId },
        callback: res => {
          console.log('指标名称列表', res);
          let arr = [];
          res.data.map((item, index) => {
            let a = {};
            a.name = item;
            a.key = index;
            arr.push(a);
          });
          this.setState({ login: false, selectList: arr }, () => {
            if (this.props.bjTime == '1') {
              // 新增
              const { textList } = this.state;
              // console.log(selectList.length,textList.length,textList,selectList)
              for (let index = 0; index < 5; index++) {
                let a = { name: '请选择', value: '', key: index };
                textList.push(a);
                this.setState({ textList });
              }
              // arr.map((item, index) => {

              // });
            }
          });
        },
      });
    });
  };

  addinds = () => {};

  // 表单数据
  userInfo = () => {
    return this.props.form.getFieldsValue();
    // 使用方法
    // let user  = this.userInfo()
    // console.log(user)
  };

  check = () => {
    let a = true;
    const { textList } = this.state;
    for (let i = 0; i < this.state.textList.length; i++) {
      const con = `content${i}`;
      this.state.textList[i].value = this.refs[con].getUeditorContent();
    }
    console.log(this.state.textList);
    setTimeout(() => {
      textList.map((item, index) => {
        if (textList[index].value === '') {
          return (a = false);
        }
      });
      if (a) {
        if (this.props.bjTime === '1') {
          // 新增
          this.businessDoAdd();
        } else {
          // 编辑
          this.businessDoEdit();
        }
      } else {
        message.error('指标内容不能为空');
      }
    }, 1);
  };

  businessDoEdit = () => {
    let user = this.userInfo();
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    const { textList } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'businessKnowledgeBase/businessDoEdit',
        payload: {
          _id: this.props.bjTime._id,
          reportType: user.select,
          endTime: moment(user.date._d).format('YYYY-MM'),
          data: textList,
        },
        callback: res => {
          console.log('编辑提交', res);
          this.setState({ login: false });
          if (!res.code) {
            message.success(`${res.msg}`);
            this.props.refresh('1');
          }
        },
      });
    });
  };

  businessDoAdd = () => {
    let user = this.userInfo();
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    const { textList } = this.state;
    let a = true;
    textList.map((item, index) => {
      if (textList[index].name === '请选择') {
        return (a = false);
      }
    });
    if (a) {
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'businessKnowledgeBase/businessDoAdd',
          payload: {
            reportType: user.select,
            endTime: moment(user.date._d).format('YYYY-MM'),
            data: textList,
          },
          callback: res => {
            console.log('新增提交', res);
            this.setState({ login: false });
            if (!res.code) {
              message.success(`${res.msg}`);
              this.props.refresh('1');
            }
          },
        });
      });
    } else {
      message.error('指标名不能为请选择');
      this.setState({ login: false });
    }
  };

  delete = val => {
    console.log(val);
    this.setState({
     valueA:val.key
    });
    const { textList } = this.state;
    if (textList.length > 1) {
      textList.map((item, index) => {
        if (textList[index].name === val.name) {
          textList.splice(index, 1);
        }
      });
      console.log(textList);
      this.setState({ textList });
    } else {
      message.error('再删除就没啦');
    }
  };

  selectNameA = (val, index) => {
    let a = true;
    // console.log(val, index);
    const { textList } = this.state;
    textList.map((item, index) => {
      if (textList[index].name === val) {
        message.error('指标名重复了');
        return (a = false);
      }
    });
    if (a) {
      textList[index].name = val;
      this.setState({ textList });
    }
  };

  textonChage = (val, index, a) => {
    // console.log(val.target.value, index, a);
    const { textList } = this.state;
    textList[index].value = val.target.value;
    this.setState({ textList });
  };

  addind = () => {
    const { selectList, textList } = this.state;
    // console.log(selectList.length,textList.length,textList,selectList)
    if (textList.length < selectList.length) {
      let a = { name: selectList[textList.length].name, value: '' };
      textList.push(a);
      this.setState({ textList });
    } else {
      message.error('无法再添加');
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { selectedRowKeys } = this.state;
    const FormItemLayont = {
      labelCol: {
        // 文字
        xs: 24,
        sm: 3,
      },
      wrapperCol: {
        // 输入框
        xs: 24,
        sm: 21,
      },
    };
    const displayp = {
      display: 'none'
    }
    return (
      <div style={{ minHeight: 'calc(100vh - 55px)', background: '#fafafa' }}>
        <Spin spinning={this.state.login}>
          <div style={{ padding: '20px 20px' }}>
            <Form layout="horizontal">
              <FormItem label="报告类型" {...FormItemLayont}>
                <div>
                  {getFieldDecorator('select', {
                    initialValue: this.state.selectPd,
                  })(
                    <Select style={{ width: 160 }}>
                      {/* <Option value="全部类型">全部类型</Option> */}
                      <Option value="财务指标">财务指标</Option>
                    </Select>
                  )}
                  <span style={{ margin: '0px 10px' }}>截至月份:</span>
                  {getFieldDecorator('date', {
                    initialValue: this.state.initalTime,
                  })(<MonthPicker style={{ width: 160 }} format={monthFormat} />)}
                </div>
              </FormItem>
              {this.state.textList.map((val, index) => {
                console.log(this.state.valueA);
                return (
                  <FormItem className="textInputZdy" style={{ background: '#fff', height: 370 }}>
                    <Tooltip placement="top" title="删除" arrowPointAtCenter>
                      <Icon
                        onClick={() => {
                          this.delete(val);
                        }}
                        style={{ fontSize: 14, float: 'right', margin: '5px 5px 0px 0px' }}
                        type="close"
                      />
                    </Tooltip>
                    <div className="opnZdy" style={{ margin: '10px 20px 10px 20px' }}>
                      <span style={{ marginRight: 5 }}>指标名称:</span>
                      <Select
                        value={val.name}
                        style={{ width: 160 }}
                        onChange={a => {
                          this.selectNameA(a, index);
                        }}
                      >
                        {this.state.selectList.map(item => {
                          return (
                            <Option size="small" value={item.name}>
                              {item.name}
                            </Option>
                          );
                        })}
                      </Select>
                    </div>
                    <div className={styles.zdywidth}>
                      {/* <TextArea
                        value={val.value}
                        onChange={a => {
                          this.textonChage(a, index, val);
                        }}
                        autosize={{ minRows: 8, maxRows: 8 }}
                        rows={8}
                      /> */}
                      <div  className={styles.csh} >
                        <Editor
                          content={val.value}
                          // height="180"
                          name={`content${index}`}
                          id={`content${index}`}
                          ref={`content${index}`}
                        />
                      </div>
                    </div>
                  </FormItem>
                );
              })}
            </Form>
          </div>
        </Spin>
        <Button onClick={this.addind} type="primary" style={{ margin: '0px 20px' }} icon="plus">
          添加指标
        </Button>
        <Button onClick={this.check} style={{ marginLeft: 0 }} type="primary">
          保存
        </Button>
        <div style={{ height: 40 }} />
      </div>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(EditorDrawer));
